import { IO } from "../common/io.js";
import * as DOM from "../functions/dom/domtool.js";
import { Color32 } from "../functions/image/color.js";
import { Target2D, ImgTool, DrawArea } from "../functions/image/image.js";
import { DrawToolCenter } from "./drawtool.js";
import { MessageDialog, ValueDesc, ValueType, ValuesDialog } from "../functions/domdialog/valuesdialog.js"
import { PixelEdit_DrawCanvas } from "./drawcanvas.js";
import { PixelEditor_Function } from "./pixeleditor_function.js";
import { History } from "./history.js";


export class Editor {

    history: History
    priview: DOM.Preview;//预览控件


    drawCanvas: PixelEdit_DrawCanvas = new PixelEdit_DrawCanvas();


    palette: DOM.PalettePanel;//调色板
    toolbox_color: DOM.Group;


    toolbox_model: DOM.Group;
    toolbox_model_bar: DOM.Toolbar;

    group_func: DOM.Panel;//左上功能区

    toolbar: DOM.Toolbar;//左中工具条
    toolbarsize: DOM.Toolbar;//左中工具条

    timer: number = 0;
    //looptimer: number = 0;
    update() {
        let time = new Date().valueOf();


        this.timer = (time % 1000) / 1000;
        // this.looptimer += delta;
        // let delta = (time - this.timer) / 1000;
        //console.log("timer=" + this.timer);


        requestAnimationFrame(this.update.bind(this));
        if (this.drawCanvas.IsSelect()) {
            this.drawCanvas.RePaint();
        }
    }
    async Init(): Promise<void> {

        this.update();
        DOM.DomTool.InitFullScreen();
        //let leftpanel1 = DOM.DomTool.AddPanel();

        //左边栏和其它
        let s1 = DOM.DomTool.AddSpliter();

        //中心区和右边栏
        let s2 = new DOM.Splitter();
        s1._panel2.AddChild(s2);
        s2.SetSplitPosRight(200);

        //左边栏上下
        let left_area = new DOM.Splitter();
        s1._panel1.AddChild(left_area);
        left_area.SetSplitPosTop(24);

        //中心区上下
        let center_area = s2._panel1;
        //center_area._root.style.backgroundColor = "#000";

        //右区上下
        let right_area = new DOM.Splitter();
        s2._panel2.AddChild(right_area);
        right_area.SetSplitPosTop(225);

        //左边栏上区
        let group = this.group_func = new DOM.Panel();
        this.group_func.Style_Fill();
        left_area._panel1.AddChild(group);


        //工具区分割
        let left_tool_area = new DOM.Splitter();
        left_area._panel2.AddChild(left_tool_area);
        left_tool_area.SetSplitPosTop(214);




        //  工具区
        let toolbox = new DOM.Group();
        toolbox.SetTitle("工具");
        toolbox._root.style.backgroundColor = "#33c";
        left_tool_area._panel1.AddChild(toolbox);

        let dotsize = new DOM.Splitter();
        dotsize.SetSplitPosTop(32);

        toolbox._panel.AddChild(dotsize);


        this.toolbarsize = new DOM.Toolbar();
        this.toolbarsize._root.style.backgroundColor = "#33c";
        this.toolbarsize.addButton("media/dot1.png", "1", "1x1像素画笔");
        this.toolbarsize.addButton("media/dot2.png", "2", "2x2像素画笔");
        this.toolbarsize.addButton("media/dot4.png", "4", "4x4像素画笔");
        this.toolbarsize.onPick = (stag) => {
            let dot = parseInt(stag);
            let tag = this.toolbar.getPickTag();
            let tool = DrawToolCenter.GetDrawTool(tag);
            if (tool != undefined) {
                tool.SetLineWidth(dot);
            }
        }
        dotsize._panel1.AddChild(this.toolbarsize);

        this.toolbar = new DOM.Toolbar();
        dotsize._panel2.AddChild(this.toolbar);
        this.toolbar.onPick = (tag) => {
            let dot = parseInt(this.toolbarsize.getPickTag());
            let tool = DrawToolCenter.GetDrawTool(tag);
            if (tool != undefined) {
                tool.SetLineWidth(dot);
                tool.OnSet();
            }
        }

        this.toolbar._root.style.backgroundColor = "#aaa";
        // 色板
        let toolbox_color = this.toolbox_color = new DOM.Group();
        toolbox_color.SetTitle("色板");
        left_tool_area._panel2.AddChild(toolbox_color);

        let pal = this.palette = new DOM.PalettePanel();
        toolbox_color._panel.AddChild(pal);
        toolbox_color.setBackColor(pal.colors[3]);

        toolbox_color.Show();

        let toolbox_template = this.toolbox_model = new DOM.Group();
        this.toolbox_model_bar = new DOM.Toolbar();
        toolbox_template._panel.AddChild(this.toolbox_model_bar);

        toolbox_template.SetTitle("模板");
        left_tool_area._panel2.AddChild(toolbox_template);
        toolbox_template.Hide();

        let pallastindex = pal.pickindex;
        pal.onPick = (index, indexhide) => {
            if (indexhide == 0)
                indexhide = 1;
            this.setBackColor(pal.colors[indexhide], false);
            if (index == 0) {
                this.toolbar.setPickTag("earse");
                pal.pickindex = pallastindex;
                pal.Update();
                if (pal.pickindex == 0)
                    pal.pickindex = 1;


            }
            else {
                pallastindex = index
            }
            this.setDrawColor(pal.colors[pal.pickindex], false);

        }

        let img = new DOM.Picture();
        img.Style_Fill();
        pal._root.childNodes[0].appendChild(img._root);

        img.setSrc(IO.GetPluginUrl("media/tran.png"));

        //中心绘图区
        let canvas = this.drawCanvas.canvas = new DOM.Canvas();
        center_area.AddChild(canvas);

        //右上预览区
        let priview = this.priview = new DOM.Preview();
        right_area._panel1.AddChild(priview);


        let right_tool = new DOM.Splitter();
        right_area._panel2.AddChild(right_tool);
        right_tool.SetSplitPosTop(260);

        let grouprgb = new DOM.Group();
        grouprgb.SetTitle("HSV调色板");



        right_tool._panel1.AddChild(grouprgb);

        let palsplit = new DOM.Splitter();
        palsplit.SetSplitPosTop(196);
        grouprgb._panel.AddChild(palsplit);
        let palrgb = new DOM.PaletteRGBPanel();
        palsplit._panel1.AddChild(palrgb);
        let label = new DOM.Label("当前颜色");
        palsplit._panel2.AddChild(label);

        palrgb.onPick = (c) => {
            label.SetText("" + c.toString());
        }
        {
            let btn = new DOM.Button("设置前景", () => {
                let c = palrgb.getPickColor().ToColor32();
                this.setDrawColor(c, false);
            });
            palsplit._panel2.AddChild(btn);

            let btn2 = new DOM.Button("设置色板", () => {
                let c = palrgb.getPickColor().ToColor32();
                this.palette.colors[this.palette.pickindex].R = c.R;
                this.palette.colors[this.palette.pickindex].G = c.G;
                this.palette.colors[this.palette.pickindex].B = c.B;
                this.palette.Update();
                this.setDrawColor(c, true);
            });
            palsplit._panel2.AddChild(btn2);
        }


        let temps = new DOM.Group();
        temps.SetTitle("图层");
        temps._panel.AddChild(new DOM.Label(".png 文件不支持图层编辑"));

        right_tool._panel2.AddChild(temps);

        //加载图片和配置
        let pngfile = IO.GetEditBaseName() + ".png";
        //let layerfile = IO.GetEditBaseName() + ".ttimg.json";
        try {
            let file = await IO.LoadBinaryFile(pngfile);
            let img = await ImgTool.Bin2ImgAsync(file);
            this.drawCanvas.SetSize(img.width, img.height);
            this.drawCanvas.getCurrentLayer().DrawArea_Init(img);
        }
        catch (e) {
            console.error(e);
            this.drawCanvas.SetSize(32, 32);
            this.drawCanvas.getCurrentLayer().updateBitmap();
        }
        // try {
        //     let layer = await IO.LoadTextFile(layerfile);
        //     let layerjson = JSON.parse(layer);
        // }
        // catch (e) {
        //     console.error(e);
        // }


        this.history = new History(this, 20);

        this.history.TrySave("打开文件" + this.drawCanvas.getWidth() + "x" + this.drawCanvas.getHeight());
        priview.SetImg(this.drawCanvas.GetFinalBitmap());


        //这是data，他不能直接渲染，需要一个backcanvas 转手
        //this._imgedit = await ImgTool.Img2Data(img);
        this.drawCanvas.Init(this);

        PixelEditor_Function.InitFunc(this);


        // this.priview.setBackColor(pal.colors[1]);
        // this.drawCanvas.canvas.setBackColor(pal.colors[1]);
        // this.palette.setBackColor(pal.colors[1]);
        this.setDrawColor(pal.colors[1], false);
        this.setBackColor(pal.colors[3], false);

        DrawToolCenter.Init(this);

    }

    setDrawColor(color: Color32, updatepickindex: boolean): void {
        this.drawCanvas.setDrawColor(color);
        this.toolbox_color.setBackColor(color);
        if (updatepickindex) {
            for (let i = 1; i < this.palette.colors.length; i++) {
                if (this.palette.colors[i].R == color.R &&
                    this.palette.colors[i].G == color.G &&
                    this.palette.colors[i].B == color.B) {
                    this.palette.pickindex = i;
                    break;
                }
            }
            this.palette.Update();
        }
    }
    setBackColor(color: Color32, updatepickindex: boolean): void {
        this.priview.setBackColor(color);
        this.drawCanvas.setBackColor(color);
        this.palette.setBackColor(color);
        if (updatepickindex) {
            for (let i = 1; i < this.palette.colors.length; i++) {
                if (this.palette.colors[i].R == color.R &&
                    this.palette.colors[i].G == color.G &&
                    this.palette.colors[i].B == color.B) {
                    this.palette.pickindexhide = i;
                    break;
                }
            }
        }
    }
    menu: DOM.Menu;

    //保存文档
    async _save() {
        let b = await this.drawCanvas.GetFinalBitmap().getCanvas().convertToBlob({ "type": "image/png" });
        let ab = await b.arrayBuffer();
        let pngdata = new Uint8Array(ab);
        //进来的时候有可能不是从png来的
        //还可能是ttimg.json
        let pngfile = IO.GetEditBaseName() + ".png";
        //let infofile = IO.GetEditBaseName() + ".ttimg.json";
        IO.SaveBinaryFile(pngfile, pngdata);
        //IO.SaveTextFile(infofile, "not implement yet.");
    }


}
export async function Tool_PixelEditInit() {
    let editor = new Editor();
    await editor.Init();
}